/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    public class LIBindings
    {
        private static string _passWord = String.Empty;

        /// <summary>
        /// 
        /// </summary>
        public static void Init()
        {
            Oceanside.LoginWindow.Keypad.SetNumericKeyCallbackDel((KeyPad.NumericKeyCallbackDelType)NumericKeyPressed);
            Oceanside.LoginWindow.Keypad.SetOkKeyCallbackDel((KeyPad.OkCallbackDelType)OkKeyPressed);
            Oceanside.LoginWindow.Keypad.SetClearKeyCallbackDel((KeyPad.ClearCallbackDelType)ClearKeyPressed);
        }


        /// <summary>
        /// 
        /// </summary>
        public static void OkKeyPressed()
        {
            try
            {
                Login(_passWord, false);
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        public static void PrepareForScreenChange_NOTHROW()
        {
            ///Reset this flag every time we lock the screen.  This will take away manager 
            ///permissions from the user if they were obtained by a card swipe.
            PosWindow.ManagerCardWasSwiped = false;
            PosWindow.ManagerIdThatSwiped = 0;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="val"></param>
        private static void NumericKeyPressed(int val)
        {
            _passWord = _passWord + val;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="password"></param>
        /// <param name="isMagnetic"></param>
        /// <param name="ignoreRemoteSession"></param>
        public static void Login(string password, bool isMagnetic, bool ignoreRemoteSession = false)
        {
            try
            {
                if (!String.IsNullOrEmpty(password))
                {
                    Constants.IsTrainingMode = false;
                    SHIFT.InitGlobalContext();
                    SHIFT.SetContextToNoTracking();

                    USER currentUser = USER.ValidatePassword(password, isMagnetic);
                    if (currentUser != null)
                    {
                        if (currentUser.IsTraining != null && ((bool)currentUser.IsTraining))
                        {
                            Constants.IsTrainingMode = true;
                            SHIFT.InitGlobalContext();
                            SHIFT.SetContextToNoTracking();
                            currentUser = USER.ValidatePassword(password, isMagnetic);

                            if (currentUser == null)
                            {
                                return;
                            }
                        }
                        else
                        {
                            Constants.IsTrainingMode = false;
                        }

                        ///This will update the test mode string.
                        NotifyingDateAndTime.UpdateTimes();


                        BUSINESS_DAY busDay = BUSINESS_DAY.GetNow(SHIFT.GlobalContext);
                        SHIFT session = SHIFT.GetNow(SHIFT.GlobalContext, busDay, currentUser);

                        if (session != null && busDay != null)
                        {
                            if (!ignoreRemoteSession && (session.IsLocked && session.LastKioskId != KIOSK.Get(SHIFT.GlobalContext).Id))
                            {
                                var q = from n in SHIFT.GlobalContext.KIOSKS where n.Id == session.LastKioskId select n;
                                string kioskName = "another terminal";

                                if (q.Any())
                                {
                                    kioskName = q.First().Name;
                                }
                                AskToIgnoreSessionLock(kioskName, password, isMagnetic);
                            }
                            else
                            {
                                if (currentUser.HasAssignedRoles())
                                {
                                    SHIFT.Current = session;

                                    ///Make sure they don't have the requirement to use a magstripe card only.
                                    if (isMagnetic || !currentUser.CheckForMagStripeRequirement())
                                    {
                                        SHIFT.Current.Lock();
                                        SHIFT.Current.SwitchToMyScreen();
                                    }
                                    else
                                    {
                                        if (currentUser.LoginMagPassword == null)
                                        {
                                            UMD.ShowGuiMessageSTASafe_NOTHROW("Your access privileges require you to magnetically swipe into the system, but you have not set a magnetic card password yet.  Please perform this action on the Time Clock screen.");
                                            SHIFT.Current.Lock();
                                            SHIFT.Current.SwitchToMyScreen();
                                        }
                                        else
                                        {
                                            UMD.ShowGuiMessageSTASafe_NOTHROW("Your access privileges require you to magnetically swipe into the system.");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (password.Equals("0000"))
                        {
                            PosWindow.MainPosWindow.Close();
                        }
                        else
                        {
                            UMD.ShowGuiMessageSTASafe_NOTHROW("You have entered an invalid passcode.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
                UMD.ShowGuiMessageSTASafe_NOTHROW("The system encountered a problem while trying to validate your password.  Please try again.");
            }
            finally
            {
                ClearKeyPressed();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="terminalName"></param>
        /// <param name="password"></param>
        /// <param name="isMagLogin"></param>
        private static void AskToIgnoreSessionLock(String terminalName, string password, bool isMagLogin)
        {
            App.InvokeStopStoryBoard_NOTHROW();

            YesNoBox ynb = new YesNoBox("WARNING: Someone has your user session locked at " + terminalName + ".  This can occur if you forgot to lock the screen at " + terminalName + ", another person is currently using your account or if the system was improperly shutdown.  If none of the preceding are true you can continue to login, however if you did leave your account session open at another terminal, choosing to login here could cause corrupted data.  Ask yourself, \"Is anyone using my account right now?\"  Would you like to login anyway?");

            ynb.ShowDialog();

            if (YesNoBox.LastResponse == UserResponse.YES)
            {
                Login(password, isMagLogin, true);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="cardNumber"></param>
        private static void ValidateLoginCard(String cardNumber)
        {
            Login(cardNumber, true);
        }

        /// <summary>
        /// 
        /// </summary>
        private static void ClearKeyPressed()
        {
            _passWord = "";
        }
    }
}
